package com.mercycrazy.springframework.beans.factory.support;

import com.mercycrazy.springframework.beans.BeansException;
import com.mercycrazy.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * JDK 实例化策略
 *
 * @author <a href="mailto:1443424326@qq.com">mercycrazy</a>
 * @since 2022-11-24
 */
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName,
                              Constructor<?> ctor, Object[] args) throws BeansException {

        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (null != ctor) {
                return clazz.getDeclaredConstructor(ctor.getParameterTypes()).newInstance(args);
            } else {
                return clazz.getDeclaredConstructor().newInstance();
            }
        } catch (InvocationTargetException | IllegalAccessException
                 | NoSuchMethodException | InstantiationException e) {
            throw new BeansException("Failed to instantiate [" + clazz.getName() + "]", e);
        }
    }
}
